﻿using gt.framework.Cache;
using gt.framework.Utils;
using System;
using System.Collections.Generic;
using System.Configuration;

namespace gt.framework.Configuration
{
    public sealed class CentralManagerConfigCreator
    {
        private const string _defaultConfigManagerPath = "~/Configs/ConfigManager.config";
        private static readonly string _configManagerPath = null;

        static CentralManagerConfigCreator()
        {
            _configManagerPath = ConfigurationManager.AppSettings["Framework:ConfigManagerPath"];
            if (string.IsNullOrEmpty(_configManagerPath))
            {
                _configManagerPath = _defaultConfigManagerPath;
            }
        }

        public static ManagerConfigBase CreatedManagerConfig()
        {
            string configManagerKey = (new ConfigManagerConfig()).GetConfigKey();
            ConfigManagerConfig instance = CacheManager.Get<ConfigManagerConfig>(configManagerKey);
            if (instance == null)
            {
                lock (typeof(ConfigManagerConfig))
                {
                    instance = CacheManager.Get<ConfigManagerConfig>(configManagerKey);
                    if (instance == null)
                    {
                        string fullPath = GetFullPath();
                        instance = ConfigManager.InvokeGetConfig<ConfigManagerConfig>(fullPath);

                        if (instance == null) throw new InvalidOperationException("can not serialize file:" + fullPath);

                        CacheManager.Insert<ConfigManagerConfig>(configManagerKey, instance, null, new List<string> { fullPath }, (o) =>
                           {
                               instance.ConfigChanged();
                           });
                    }
                }
            }
            return instance;
        }

        private static string GetFullPath()
        {
            return PathUtils.GetFullPath(_configManagerPath);
        }

        public static string GetAppDataByConfigKey(string configKey)
        {
            string fullPath = GetFullPath();
            ManagerConfigBase configBase = ConfigManager.InvokeGetConfig<ConfigManagerConfig>(fullPath);

            if (configBase != null)
            {
                return configBase.GetConfigPath(configKey);
            }

            return null;
        }
    }
}
